package main

import (
	"gopkg.in/ini.v1"
	"sync"
	"tansi/logagent/conf"
	"tansi/logagent/etcd"
	"tansi/logagent/kafka"
	"tansi/logagent/taillog"
	"tansi/logagent/utils"
	"time"
	"fmt"
)

// logAgent入口程序

var (
	cfg = new(conf.AppConfig)
)

/*
func run(){
	// 1.读取日志
	for {
		select {
		case line :=  <- taillog.ReadChan():
			// 2.发送到kafka
			kafka.SendToKafka()
		default:
			time.Sleep(time.Second)
		}
	}
}
*/


func main(){
	// 0.加载配置文件
	err := ini.MapTo(cfg, "./conf/config.ini")
	if err != nil{
		fmt.Printf("load ini failed,err: %v\n", err)
		return
	}

	// 1.初始化kafka连接
	err = kafka.Init([]string{cfg.KafkaConfig.Address}, cfg.KafkaConfig.ChanMaxSize)
	if err != nil{
		fmt.Printf("init kafka failed,err: %v\n", err)
		return
	}
	fmt.Println("init kafka success!")

	// 2.初始化etcd
	err = etcd.Init(cfg.EtcdConf.Address, time.Duration(cfg.EtcdConf.Timeout)*time.Second)
	if err != nil{
		fmt.Printf("init etcd failed,err:%v\n", err)
		return
	}
	fmt.Println("init etcd success.")
	// 为了实现每个logagent都拉取自己独有的配置，所以要以自己的IP地址作为区分
	ipStr, err := utils.GetOutboundIP()
	if err != nil{
		panic(err)
	}

	etcdConfKey := fmt.Sprintf(cfg.EtcdConf.Key, ipStr)

	// 2.1从etcd中获取日志收集项的配置信息
	logEntryConf, err := etcd.GetConf(etcdConfKey)


	if err != nil{
		fmt.Printf("get conf failed,err:%v\n", err)
		return
	}
	fmt.Printf("get conf from etcd success,%v\n",logEntryConf)
	// 2.2 派一个哨兵去监视日志收集项的变化(有变化及时通知我的logAgent)




	for index, value := range logEntryConf{
		fmt.Printf("index:%v, value:%v\n",index,value)
	}


	// 3.收集日志发往kafka
	taillog.Init(logEntryConf)
	// 因为newConfChan因为tskMgr的newConfChan，这个channel是在taillog.Init(logEntryConf)执行的初始化
	newConfChan := taillog.NewConfChan()	// 从taillog包中获取对外暴露的通道
	var wg sync.WaitGroup
	wg.Add(1)
	go etcd.WatchConf(etcdConfKey, newConfChan)	// 哨兵发现最新的配置信息会通知上面的那个通道
	wg.Wait()

	// 2.打开日志文件准备收集日志
	//err = taillog.Init(cfg.TailLogConf.FileName)
	//if err != nil{
	//	fmt.Printf("Init taillog failed,err: %v\n", err)
	//	return
	//}
	//fmt.Println("init taillog success!")
	// 3.具体的业务
	//run()

}